<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-semibold text-gray-800">消耗查询</h2>
      <button @click="exportReport" class="flex items-center px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
        <ArrowDownTrayIcon class="h-5 w-5 mr-2" />
        导出报表
      </button>
    </div>

    <!-- Query Filters -->
    <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
      <form @submit.prevent="handleSearch" class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label for="semester" class="block text-sm font-medium text-gray-700">学期</label>
          <select id="semester" v-model="queryForm.semester" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <option value="">请选择学期</option>
            <option value="2024年春季学期">2024年春季学期</option>
            <option value="2024年秋季学期">2024年秋季学期</option>
            <option value="2025年春季学期">2025年春季学期</option>
            <option value="2025年秋季学期">2025年秋季学期</option>
          </select>
        </div>
        <div>
          <label for="laboratory" class="block text-sm font-medium text-gray-700">实验室</label>
          <select id="laboratory" v-model="queryForm.laboratory" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <option value="">请选择实验室</option>
            <option value="计算机实验室A">计算机实验室A</option>
            <option value="计算机实验室B">计算机实验室B</option>
            <option value="化学实验室">化学实验室</option>
            <option value="生物实验室">生物实验室</option>
            <option value="物理实验室">物理实验室</option>
          </select>
        </div>
        <div>
          <label for="itemName" class="block text-sm font-medium text-gray-700">物品名称</label>
          <input type="text" id="itemName" v-model="queryForm.itemName" placeholder="请输入物品名称" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
        </div>
        <div>
          <label for="dateRange" class="block text-sm font-medium text-gray-700">日期范围</label>
          <input type="date" id="dateRange" v-model="queryForm.dateRange" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
        </div>
        <div class="md:col-span-4 flex justify-end space-x-3 mt-4">
          <button type="submit" class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">查询</button>
          <button type="button" @click="handleReset" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">重置</button>
        </div>
      </form>
    </div>

    <!-- Summary Cards -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
      <div class="bg-white rounded-xl shadow-lg p-5 flex items-center space-x-4">
        <div class="flex-shrink-0 bg-indigo-100 p-3 rounded-full">
          <ClipboardDocumentListIcon class="h-6 w-6 text-indigo-600" />
        </div>
        <div>
          <p class="text-gray-500 text-sm">总消耗项目</p>
          <p class="text-2xl font-semibold text-gray-900">{{ summary.totalItems }}</p>
        </div>
      </div>
      <div class="bg-white rounded-xl shadow-lg p-5 flex items-center space-x-4">
        <div class="flex-shrink-0 bg-green-100 p-3 rounded-full">
          <CubeIcon class="h-6 w-6 text-green-600" />
        </div>
        <div>
          <p class="text-gray-500 text-sm">总消耗数量</p>
          <p class="text-2xl font-semibold text-gray-900">{{ summary.totalQuantity }}</p>
        </div>
      </div>
      <div class="bg-white rounded-xl shadow-lg p-5 flex items-center space-x-4">
        <div class="flex-shrink-0 bg-yellow-100 p-3 rounded-full">
          <BanknotesIcon class="h-6 w-6 text-yellow-600" />
        </div>
        <div>
          <p class="text-gray-500 text-sm">总消耗金额</p>
          <p class="text-2xl font-semibold text-gray-900">¥{{ summary.totalAmount.toLocaleString() }}</p>
        </div>
      </div>
      <div class="bg-white rounded-xl shadow-lg p-5 flex items-center space-x-4">
        <div class="flex-shrink-0 bg-blue-100 p-3 rounded-full">
          <ChartBarIcon class="h-6 w-6 text-blue-600" />
        </div>
        <div>
          <p class="text-gray-500 text-sm">平均消耗率</p>
          <p class="text-2xl font-semibold text-gray-900">{{ summary.averageConsumptionRate }}%</p>
        </div>
      </div>
    </div>

    <!-- Consumption Analysis Chart -->
    <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
      <h3 class="text-xl font-semibold text-gray-800 mb-4">消耗趋势分析</h3>
      <div ref="consumptionChart" class="w-full h-80"></div>
    </div>

    <!-- Laboratory Comparison Chart -->
    <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
      <h3 class="text-xl font-semibold text-gray-800 mb-4">实验室消耗对比</h3>
      <div ref="laboratoryChart" class="w-full h-80"></div>
    </div>

    <!-- Detailed Consumption Table -->
    <div class="bg-white rounded-xl shadow-lg p-6">
      <h3 class="text-xl font-semibold text-gray-800 mb-4">详细消耗记录</h3>
      <div v-if="loading" class="text-center py-8">加载中...</div>
      <div v-else class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">物品名称</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">规格型号</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">计划数量</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">实际消耗</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">消耗率</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">实验室</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学期</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="record in consumptionRecords" :key="record.id">
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ record.itemName }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ record.specification }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ record.plannedQuantity }} {{ record.unit }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ record.actualConsumption }} {{ record.unit }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                <span :class="['px-2 inline-flex text-xs leading-5 font-semibold rounded-full', getConsumptionRateClass(record.consumptionRate)]">
                  {{ record.consumptionRate }}%
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ record.laboratory }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ record.semester }}</td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- Pagination -->
      <div class="flex justify-end mt-6">
        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
          <button @click="handleCurrentChange(pagination.current - 1)" :disabled="pagination.current === 1" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
            <span class="sr-only">Previous</span>
            <ChevronLeftIcon class="h-5 w-5" aria-hidden="true" />
          </button>
          <button v-for="page in totalPages" :key="page" @click="handleCurrentChange(page)" :class="['relative inline-flex items-center px-4 py-2 border text-sm font-medium', page === pagination.current ? 'z-10 bg-indigo-50 border-indigo-500 text-indigo-600' : 'bg-white border-gray-300 text-gray-700 hover:bg-gray-50']">
            {{ page }}
          </button>
          <button @click="handleCurrentChange(pagination.current + 1)" :disabled="pagination.current === totalPages" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
            <span class="sr-only">Next</span>
            <ChevronRightIcon class="h-5 w-5" aria-hidden="true" />
          </button>
        </nav>
        <div class="ml-4 flex items-center text-sm text-gray-700">
          <span>共 {{ pagination.total }} 条</span>
          <select v-model="pagination.size" @change="handleSizeChange($event.target.value)" class="ml-2 block w-auto pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md">
            <option :value="10">10 条/页</option>
            <option :value="20">20 条/页</option>
            <option :value="50">50 条/页</option>
            <option :value="100">100 条/页</option>
          </select>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import request from '@/utils/request'
import {
  ArrowDownTrayIcon,
  ClipboardDocumentListIcon,
  CubeIcon,
  BanknotesIcon,
  ChartBarIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
} from '@heroicons/vue/24/outline'
import * as echarts from 'echarts'

const consumptionRecords = ref([])
const loading = ref(false)

const queryForm = reactive({
  semester: '',
  laboratory: '',
  itemName: '',
  dateRange: ''
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const summary = reactive({
  totalItems: 0,
  totalQuantity: 0,
  totalAmount: 0,
  averageConsumptionRate: 0,
})

const laboratoryComparison = reactive({})

// 图表相关变量
const consumptionChart = ref(null)
const laboratoryChart = ref(null)

const totalPages = computed(() => Math.ceil(pagination.total / pagination.size))

// Get consumption rate class
const getConsumptionRateClass = (rate) => {
  if (rate >= 90) return 'bg-red-100 text-red-800'
  if (rate >= 70) return 'bg-yellow-100 text-yellow-800'
  return 'bg-green-100 text-green-800'
}

// Export report
const exportReport = () => {
  showMessage('导出报表功能待开发', 'info')
  // Implement Excel export logic here
}

// Search
const handleSearch = () => {
  pagination.current = 1
  loadConsumptionRecords()
}

// Reset search
const handleReset = () => {
  Object.assign(queryForm, {
    semester: '',
    laboratory: '',
    itemName: '',
    dateRange: ''
  })
  pagination.current = 1
  loadConsumptionRecords()
}

// Page size change
const handleSizeChange = (size) => {
  pagination.size = parseInt(size)
  pagination.current = 1
  loadConsumptionRecords()
}

// Current page change
const handleCurrentChange = (current) => {
  if (current < 1 || current > totalPages.value) return
  pagination.current = current
  loadConsumptionRecords()
}

// Load consumption records
const loadConsumptionRecords = async () => {
  try {
    loading.value = true
    
    // 调用新的消耗查询API
    const queryParams = {
      current: pagination.current,
      size: pagination.size,
      laboratoryId: queryForm.laboratory || undefined,
      itemName: queryForm.itemName || undefined
    }

    const response = await request.get('/consumable-receives/consumption-query', { params: queryParams })
    consumptionRecords.value = response.data.records.map(record => ({
      id: record.id,
      itemName: record.itemName,
      specification: record.specification,
      plannedQuantity: record.plannedQuantity,
      actualConsumption: record.actualQuantity,
      unit: record.unit,
      consumptionRate: record.consumptionRate,
      laboratory: record.laboratoryName,
      semester: record.semester
    }))
    pagination.total = response.data.total

    // Calculate summary
    summary.totalItems = response.data.total
    summary.totalQuantity = response.data.records.reduce((sum, record) => sum + record.actualQuantity, 0)
    summary.totalAmount = response.data.records.reduce((sum, record) => sum + record.actualAmount, 0)
    
    // 计算平均消耗率
    const totalConsumptionRate = response.data.records.reduce((sum, record) => sum + (record.consumptionRate || 0), 0)
    summary.averageConsumptionRate = response.data.records.length > 0 ? 
      Math.round(totalConsumptionRate / response.data.records.length * 100) / 100 : 0

    // 计算实验室对比数据
    const labStats = {}
    response.data.records.forEach(record => {
      const labName = record.laboratoryName
      if (!labStats[labName]) {
        labStats[labName] = { amount: 0, quantity: 0 }
      }
      labStats[labName].amount += record.actualAmount
      labStats[labName].quantity += record.actualQuantity
    })
    
    // 更新实验室对比数据
    Object.keys(laboratoryComparison).forEach(key => delete laboratoryComparison[key])
    Object.assign(laboratoryComparison, labStats)

    // 初始化图表
    await initCharts()

  } catch (error) {
    console.error('加载消耗记录失败:', error)
    showMessage('加载消耗记录失败', 'error')
  } finally {
    loading.value = false
  }
}

// 初始化图表
const initCharts = async () => {
  await nextTick()
  
  // 初始化消耗趋势图表
  if (consumptionChart.value) {
    const chart = echarts.init(consumptionChart.value)
    const option = {
      title: {
        text: '消耗趋势分析',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['计划数量', '实际消耗', '消耗率'],
        top: 30
      },
      xAxis: {
        type: 'category',
        data: consumptionRecords.value.map(record => record.itemName)
      },
      yAxis: [
        {
          type: 'value',
          name: '数量',
          position: 'left'
        },
        {
          type: 'value',
          name: '消耗率(%)',
          position: 'right'
        }
      ],
      series: [
        {
          name: '计划数量',
          type: 'bar',
          data: consumptionRecords.value.map(record => record.plannedQuantity),
          itemStyle: { color: '#3b82f6' }
        },
        {
          name: '实际消耗',
          type: 'bar',
          data: consumptionRecords.value.map(record => record.actualConsumption),
          itemStyle: { color: '#10b981' }
        },
        {
          name: '消耗率',
          type: 'line',
          yAxisIndex: 1,
          data: consumptionRecords.value.map(record => record.consumptionRate),
          itemStyle: { color: '#f59e0b' }
        }
      ]
    }
    chart.setOption(option)
  }
  
  // 初始化实验室对比图表
  if (laboratoryChart.value) {
    const chart = echarts.init(laboratoryChart.value)
    const labNames = Object.keys(laboratoryComparison)
    const labAmounts = labNames.map(name => laboratoryComparison[name].amount)
    const labQuantities = labNames.map(name => laboratoryComparison[name].quantity)
    
    const option = {
      title: {
        text: '实验室消耗对比',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['消耗金额', '消耗数量'],
        top: 30
      },
      xAxis: {
        type: 'category',
        data: labNames
      },
      yAxis: [
        {
          type: 'value',
          name: '金额(¥)',
          position: 'left'
        },
        {
          type: 'value',
          name: '数量',
          position: 'right'
        }
      ],
      series: [
        {
          name: '消耗金额',
          type: 'bar',
          data: labAmounts,
          itemStyle: { color: '#8b5cf6' }
        },
        {
          name: '消耗数量',
          type: 'bar',
          yAxisIndex: 1,
          data: labQuantities,
          itemStyle: { color: '#06b6d4' }
        }
      ]
    }
    chart.setOption(option)
  }
}

onMounted(() => {
  loadConsumptionRecords()
})

// Simple message display function (can be moved to a global utility)
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}
</script>
